package com.jblv.frame.user.service.config;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.jblv.frame.common.type.BooleanType;
import com.jblv.frame.user.api.handler.MyBatisPlusMetaObjectHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title MybatisPlusConfig
 * @projectName jblv-frame
 * @packageName com.jblv.user.service.config
 * @description MybatisPlusConfig
 * @date Create at 2020/4/22 11:50
 * @since jdk1.8
 */
@Configuration
@MapperScan("com.jblv.**.mapper.*")
public class MybatisPlusConfig  implements EnvironmentAware{
    private static final Logger logger = LoggerFactory.getLogger(MybatisPlusConfig.class);

    private Environment environment;

    private static Properties propertyResolver;

    @Override
    public   void setEnvironment(Environment env) {
        environment = env;
        Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
        Binder binder = new Binder(sources);
        BindResult<Properties> bindResult = binder.bind("mybatis", Properties.class);
        propertyResolver = bindResult.get();
    }

    @Bean
    public GlobalConfiguration globalConfiguration() {
        GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
        //逻辑删除配置
        conf.setLogicDeleteValue(BooleanType.TRUE.getCode()+"");
        conf.setLogicNotDeleteValue(BooleanType.FALSE.getCode()+"");
//        conf.setSqlInjector();
        //主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
        conf.setIdType(2);
        //字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
        conf.setFieldStrategy(2);
        //配置自动填充字段
        conf.setMetaObjectHandler(new MyBatisPlusMetaObjectHandler());
        return conf;
    }

    @Bean
    public   PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType(propertyResolver.getProperty("dbType"));// mysql
        logger.info("分页配置完成");
        return page;
    }


    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, ResourceLoader resourceLoader, GlobalConfiguration globalConfiguration) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);

        Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources(propertyResolver.getProperty("mapper-locations"));
        sqlSessionFactory.setTypeAliasesPackage(propertyResolver.getProperty("aliasesPackege"));// "com.innochina.platform.linkservice.autogenerator.entity");

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),
                new PerformanceInterceptor(),
                new OptimisticLockerInterceptor()
        });
        sqlSessionFactory.setGlobalConfig(globalConfiguration);
        logger.info("sqlSqlSession配置完成");
        return sqlSessionFactory.getObject();

    }


    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfig = new MapperScannerConfigurer();
        scannerConfig.setBasePackage(propertyResolver.getProperty("mapperBasePackage"));// "com.innochina.platform.linkservice.autogenerator.mapper");
        scannerConfig.setSqlSessionFactoryBeanName("sqlSessionFactory");
        logger.info("mapperScannerConfigurer配置完成");
        return scannerConfig;
    }
}
